package Utils;

import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.UpdateOptions;
import org.bson.Document;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class Tools {
    static ChromeOptions chromeOptions = new ChromeOptions();

    // 设置后台静默模式启动浏览器
    static{
        chromeOptions.addArguments("--headless");
    }

//    static {
//        System.setProperty("webdriver.chrome.driver", "D:\\Selenium_Driver\\chromedriver.exe");
//    }
//
//    static ChromeDriver driver = new ChromeDriver();

    public static void consoleInfo(String msg) {
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("[" + ft.format(new Date()) + "] - " + msg);
    }

    public static List<String> getDateList(String startDateStr, String endDateStr) {
        /**
         * 解析startDate至endDate之间所有的日期，转换成str，组成list返回
         *
         */
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        List<String> dateList = new ArrayList<>();
        try {
            Date startDate = simpleDateFormat1.parse(startDateStr);
            Date endDate = simpleDateFormat1.parse(endDateStr);
            Calendar calendar = Calendar.getInstance();
            for (Date i = startDate; endDate.compareTo(i) >= 0; i = calendar.getTime()) {
                dateList.add(simpleDateFormat1.format(i));
                calendar.setTime(i);
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("检查日期格式（yyyy-MM-dd）！");
            return null;
        }

        return dateList;
    }


    public static void updateToDb(MongoCollection collection, Document doc) {
        BasicDBObject query = new BasicDBObject().append("_id", doc.get("_id"));
        BasicDBObject obj = new BasicDBObject("$set", doc);
        collection.updateOne(query, obj, (new UpdateOptions()).upsert(true));
        consoleInfo("update to db: " + doc);
    }

    public static String getCookie() {
        String[] deleteCookies = {"expires=", "path=", "domain=", "secure"};
        try {
            String originCookieStr = getOriginCookie();
            originCookieStr = originCookieStr.replaceAll("\\[|\\]|,", "");

            String[] cookies = originCookieStr.split(";");
            StringBuilder sb = new StringBuilder();
            for (String cookie : cookies) {
                Boolean flag = true;

                for (String deleteCookie : deleteCookies) {
                    if (cookie.contains(deleteCookie)) {
                        flag = false;
                        break;
                    }
                }

                if (flag)
                    sb.append(cookie.trim() + ";");
            }
            return sb.toString();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    public static String getOriginCookie() throws InterruptedException {

        //设置驱动
        System.setProperty("webdriver.chrome.driver", "D:\\Selenium_Driver\\chromedriver.exe");
        //创建ChromeDriver对象
        ChromeDriver driver = new ChromeDriver();

        //打开网页
        driver.get("https://epub.cnki.net/kns/brief/result.aspx?dbPrefix=CDMD");
        //driver.findElementById("btnSearch").click();
        Thread.sleep(2000);
        String originCookieStr = driver.manage().getCookies().toString();
        driver.quit();
        return originCookieStr;
    }
}
